import { create } from "zustand";
import { persist } from "zustand/middleware";
import { globalStorage } from '@/utils/storage';
import tokenCenter from '../utils/token';
import { message } from '@/components';
import { User } from '@/typings/user';
import { userLoginApi, fetchUserApi, type UserLoginParams } from '@/services/user';

export type UserModelType = {
  token?: string;
  user?: User.UserInfo;
  logout: () => void;
  checkToken: () => Promise<void>;
  fetchUser: () => Promise<void>;
  login: (params: UserLoginParams) => Promise<void>;
}

/**
 * 用户模块
*/
export default create(persist<UserModelType>(
  (set) => {
    return {
      checkToken: async () => {
        const token = await tokenCenter.getToken();
        set({ token });
      },
      login: async (params) => {
        try {
          const result = await userLoginApi(params);
          const token = result.access_token;
          const user = await fetchUserApi({ token });
          await tokenCenter.setToken(result);
          set({ token, user });
        } catch (err: any) {
          message.error('The account number or password is incorrect.');
        }
      },
      fetchUser: async () => {
        set({ user: await fetchUserApi() });
      },
      logout: () => {
        set({
          user: undefined,
          token: undefined
        });
      }
    };
  },
  {
    name: "user",
    storage: globalStorage
  }
));
